package com.ibm.risk.irmp.common.datasource;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.AbstractDataSource;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class DynamicDataSource extends AbstractDataSource {
    private DataSource master;
    private DataSource slave;

    protected DataSource determineTargetDataSource() {
        boolean readonly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
        log.debug("isCurrentTransactionReadOnly: {}", readonly);
        if (readonly) {
            if (slave != null) {
                log.trace("return readonly ds");
                return slave;
            }
        }
        return master;

    }

    @Override
    public Connection getConnection() throws SQLException {
        return determineTargetDataSource().getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return determineTargetDataSource().getConnection(username, password);
    }
}
